import { Teacher } from "../model/Teacher.js"
import { Op as op } from "sequelize"

let fn_list = async (ctx) => {
    let keyWrod = ctx.request.query.keyWrod || 0
    console.log(keyWrod);
    let where = null

    if (keyWrod.trim()) {
        where = {
            [op.or]: {
                teacherName: {
                    [op.like]: `%${keyWrod}%`
                },

                teacherPhone: {
                    [op.like]: `%${keyWrod}%`
                },
            }
        }
    }
    let teachers = await Teacher.findAll(
        { where: {} });

    ctx.stutas = 200;

    ctx.body = {
        code: 1000,
        msg: "列表显示成功",
        data: teachers
    }

}
let fn_ById = async (ctx) => {
    let id = ctx.params.id || 0
    let teacher = await Teacher.findByPk(id)
    ctx.body = {
        code: 1000,
        msg: '查询成功',
        data: obj
    }
}
let fn_add = async (ctx) => {
    ctx.body = "新增"
    let obj = ctx.request.body
    console.log(obj);

    if (obj) {
        let teacher = await Teacher.create(obj)
    }
    ctx.body = {
        code: 1000,
        msg: '新增成功',
        data: obj
    }
}
let fn_upd = async (ctx) => {
    ctx.body = "修改"
    let id = ctx.params.id || 0
    let obj = ctx.request.body
    let res = await Teacher.update(obj, {
        where: {
            id: id
        }
    })
    ctx.body = {
        code: 1000,
        msg: "修改成功",
        data: res
    }
}
let fn_del = async (ctx) => {
    let id = ctx.params.id || 0
    let count = await Teacher.destroy({
        where: {
            id: id
        }
    })
    let res
    if (count === 1) {
        res = {
            data: null,
            msg: "删除成功",
            code: 1000
        }
    } else {
        res = {
            data: null,
            msg: "删除失败",
            code: 4000
        }
    }
    ctx.body = res
}
export default [{
    url: "/teacher",
    method: "get",
    fn: fn_list
},
{
    url: "/teacher/:id",
    method: "get",
    fn: fn_ById
}
    ,
{
    url: "/teacher",
    method: "post",
    fn: fn_add
},
{
    url: "/teacher/:id",
    method: "put",
    fn: fn_upd
},
{
    url: "/teacher/:id",
    method: "del",
    fn: fn_del
}]


// // 错误：{where} 缺少参数
// let teachers = await Teacher.findAll({ where });

// // 修正：应传递有效的查询条件或空对象
// let teachers = await Teacher.findAll({ where: {} });
// // 